﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;

namespace Domzs.Extensions
{
    public static class EnumerableExtensions
    {
        // Usage: myList.ForEach(x => Console.Write(x)); 
        // Usage: myList.ForEach(myAction);
        public static void ForEach<T>(this IEnumerable<T> list, Action<T> action)
        {
            foreach (var item in list) action(item);
        }

        /// <summary>
        /// Unions the specified items1.
        /// </summary>
        /// <param name="items1">The items1.</param>
        /// <param name="items2">The items2.</param>
        /// <returns></returns>
        public static IEnumerable<object> Union(this IEnumerable items1, IEnumerable items2)
        {
            if (items1 != null)
                foreach (var item in items1)
                {
                    yield return item;
                }

            if (items2 != null)
                foreach (var item in items2)
                {
                    yield return item;
                }
        }

        // for generic interface IEnumerable<T>
        public static string ToString<T>(this IEnumerable<T> source, string separator)
        {
            if (source == null)
                throw new ArgumentException("Parameter source can not be null.");

            if (string.IsNullOrEmpty(separator))
                throw new ArgumentException("Parameter separator can not be null or empty.");

            string[] array = source.Where(n => n != null).Select(n => n.ToString()).ToArray();

            return string.Join(separator, array);
        }

        // for interface IEnumerable
        public static string ToString(this IEnumerable source, string separator)
        {
            if (source == null)
                throw new ArgumentException("Parameter source can not be null.");

            if (string.IsNullOrEmpty(separator))
                throw new ArgumentException("Parameter separator can not be null or empty.");

            string[] array = source.Cast<object>().Where(n => n != null).Select(n => n.ToString()).ToArray();

            return string.Join(separator, array);
        }
    }
}
